package com.ruoyi.web.controller;


import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.business.entity.YytMember;
import com.ruoyi.common.business.service.YytMemberService;
import com.ruoyi.common.sms.service.YytSmsCouponService;
import com.ruoyi.config.WeXinConfig;
import com.ruoyi.utils.*;
import com.ruoyi.vo.LogisticsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;


@RequestMapping("weixin")
@RestController
public class WeixinController {

    @Autowired
    WeXinConfig weXinConfig;

    @Autowired
    private YytMemberService yytMemberService;

    @Autowired
    private RedisService redisService;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private YytSmsCouponService yytSmsCouponService;

    /**
     * 方法名 getOpenid
     * 描述 TODO 换取微信Id
     * 作者 Jieluo
     * 时间 2021/12/24 16:00
     * @Param [request]
     */
    @GetMapping("getOpenid")
    public ResponseResult getSessionID(HttpServletRequest request){
        String code = "";
        code = request.getParameter("code");
        return ResponseResult.success(weXinConfig.getSessionId(code));
    }


    /**
     * 方法名 getUser
     * 描述 TODO 微信ID登陆
     * 作者 Jieluo
     * 时间 2021/12/24 16:00
     * @Param [request]
     */
    @PostMapping("getUser")
    public ResponseResult getUser(@RequestBody LoginParam loginParam, HttpServletRequest request){
        LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yytMemberLambdaQueryWrapper.eq(YytMember::getWechatId,loginParam.getWechatId()).eq(YytMember::getDelFlag,"0");
        YytMember member = yytMemberService.getOne(yytMemberLambdaQueryWrapper);
        // 用户不存在
        if(member==null){
            return ResponseResult.success(404);
        }
        // 用户已停用
        if(member.getStatus().equals("1")){
            throw new DisableLoginException(request.getRemoteAddr(), member.getId(), System.currentTimeMillis());
        }
        StpUtil.login(member.getId(),loginParam.getSourceType());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        //修改登录信息
        member.setLoginIp(request.getRemoteAddr());
        member.setLoginDate(LocalDateTime.now());
        yytMemberService.updateById(member);
        redisService.putNoTime(member.getId(), JSONUtil.toJsonPrettyStr(member));
        return ResponseResult.success(tokenInfo);
    }

    /**
     * 方法名 getPhone
     * 描述 TODO 微信授权换取手机号并查询有无此账号
     * 作者 Jieluo
     * 时间 2021/12/24 16:00
     * @Param [request]
     */
    @GetMapping("getPhone")
    public ResponseResult getPhone( HttpServletRequest request) throws Exception{
        String encryptedData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
        String sessionKey = request.getParameter("sessionKey");
        String sourceType = request.getParameter("sourceType");
        String f = request.getParameter("f");
        String s = weXinConfig.desEncrypt(encryptedData, sessionKey, iv);
        JSONObject info = JSON.parseObject(s, JSONObject.class);
        //if (f.equals("2")){
        //    return ResponseResult.success(info.get("phoneNumber"));
        //}
        //LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //yytMemberLambdaQueryWrapper.eq(YytMember::getPhone,info.get("phoneNumber")).eq(YytMember::getDelFlag,"0");
        //YytMember member = yytMemberService.getOne(yytMemberLambdaQueryWrapper);

        QueryWrapper<YytMember> wrapper = new QueryWrapper<>();
        YytMember member = yytMemberService.getById(request.getParameter("wechatId"));
        // 用户不存在
        if(member==null){
            return ResponseResult.success(404);
        }
        // 用户已停用
        if(member.getStatus().equals("1")){
            throw new DisableLoginException(request.getRemoteAddr(), member.getId(), System.currentTimeMillis());
        }
        StpUtil.login(member.getId(),sourceType);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        //修改登录信息
        member.setLoginIp(request.getRemoteAddr());
        member.setLoginDate(LocalDateTime.now());
        member.setPhone(info.get("phoneNumber").toString());
        yytMemberService.updateById(member);
        redisService.putNoTime(member.getId(), JSONUtil.toJsonPrettyStr(member));
        return ResponseResult.success(tokenInfo);
    }


    /**
     * 方法名 addOpenid
     * 描述 TODO 微信授权换取
     * 作者 Jieluo
     * 时间 2021/12/24 16:00
     * @Param [request]
     */
    @GetMapping("addOpenid")
    public ResponseResult addOpenid( HttpServletRequest request) throws Exception{
        String encryptedData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
        String sessionKey = request.getParameter("sessionKey");
        String sourceType = request.getParameter("sourceType");
        String wechatId = request.getParameter("wechatId");
        String s = weXinConfig.desEncrypt(encryptedData, sessionKey, iv);
        JSONObject info = JSON.parseObject(s, JSONObject.class);

        int count = 0;
        LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yytMemberLambdaQueryWrapper.eq(YytMember::getWechatId,wechatId).eq(YytMember::getDelFlag,"0");
        count = yytMemberService.count(yytMemberLambdaQueryWrapper);
        if(count>0){
            return ResponseResult.success("授权成功");
        }

        //生成加密盐
        String salt  =  WebConstants.generateNumber();
        SaSecureUtil.md5(salt);
        YytMember yytMember = new YytMember();
        yytMember.setNickname((String) info.get("nickName"));
        yytMember.setIcon((String) info.get("avatarUrl"));
        // md5加盐加密: md5(md5(str) + md5(salt))
//        yytMember.setPassword(SaSecureUtil.md5BySalt(registerVo.getPassword(), salt));
        yytMember.setSalt(salt);
        System.out.println("wechatId"+wechatId);
        yytMember.setWechatId(wechatId);
//        yytMember.setPhone(registerVo.getPhoneNumber());
        yytMember.setStatus("0");
        yytMember.setDelFlag("0");
        yytMember.setCreateBy("小程序");
        yytMember.setCreateTime(LocalDateTime.now());
        yytMemberService.save(yytMember);
        // 添加新用户优惠券
        yytSmsCouponService.addCoupon(yytMember);
        return ResponseResult.success("注册成功");
    }

    /**
     * 用户授权登录或注册
     * @return
     */
    @GetMapping("/userLoginOrAdd")
    public ResponseResult userLoginOrAdd(HttpServletRequest request) throws Exception {
        //String encryptedData = request.getParameter("encryptedData");
        //String iv = request.getParameter("iv");
        //String sessionKey = request.getParameter("sessionKey");
        //String sourceType = request.getParameter("sourceType");
        ////String s = weXinConfig.desEncrypt(encryptedData, sessionKey, iv);
        //JSONObject info = JSON.parseObject(s, JSONObject.class);
        String wechatId = request.getParameter("wechatId");
        String nickName = request.getParameter("nickName");
        String avatarUrl = request.getParameter("avatarUrl");

        QueryWrapper<YytMember> yytMemberQueryWrapper = new QueryWrapper<>();
        yytMemberQueryWrapper.eq("wechat_id", wechatId).eq("del_flag", "0").last("limit 1");
        YytMember member = yytMemberService.getOne(yytMemberQueryWrapper);

        /**
         * 导致多账号的错误代码
         */
//        LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrappers = new LambdaQueryWrapper<>();
//        yytMemberLambdaQueryWrappers.eq(YytMember::getWechatId,wechatId).eq(YytMember::getDelFlag,"0");
//        YytMember member = yytMemberService.getOne(yytMemberLambdaQueryWrappers);


        if(member != null){
            StpUtil.login(member.getId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            //修改登录信息
            member.setLoginIp(request.getRemoteAddr());
            member.setLoginDate(LocalDateTime.now());
            yytMemberService.updateById(member);
            redisService.putNoTime(member.getId(), JSONUtil.toJsonPrettyStr(member));
            return ResponseResult.success(tokenInfo);
        }

        //生成加密盐
        String salt  =  WebConstants.generateNumber();
        SaSecureUtil.md5(salt);
        YytMember yytMember = new YytMember();
        yytMember.setNickname(nickName);
        yytMember.setIcon(avatarUrl);
        // md5加盐加密: md5(md5(str) + md5(salt))
//        yytMember.setPassword(SaSecureUtil.md5BySalt(registerVo.getPassword(), salt));
        yytMember.setSalt(salt);
        System.out.println("wechatId"+wechatId);
        yytMember.setWechatId(wechatId);
//        yytMember.setPhone(registerVo.getPhoneNumber());
        yytMember.setStatus("0");
        yytMember.setDelFlag("0");
        yytMember.setCreateBy("小程序");
        yytMember.setCreateTime(LocalDateTime.now());
        yytMemberService.save(yytMember);
        StpUtil.login(yytMember.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        redisService.putNoTime(yytMember.getId(), JSONUtil.toJsonPrettyStr(yytMember));
        return ResponseResult.success(tokenInfo);
    }


    /**
     * 方法名 setPhone
     * 描述 TODO 添加（修改）手机号
     * 作者 Jieluo
     * 时间 2021/12/24 18:00
     * @Param [request]
     */
    @GetMapping("setPhone")
    public ResponseResult setPhone(HttpServletRequest request){
        String phone = request.getParameter("phone");
        String id = request.getParameter("id");
        int count = 0;
        LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yytMemberLambdaQueryWrapper.eq(YytMember::getPhone,phone).eq(YytMember::getDelFlag,"0");
        count = yytMemberService.count(yytMemberLambdaQueryWrapper);
        if(count>0){
            return ResponseResult.failure("该手机号已存在!");
        }
        YytMember yytMember = new YytMember();
        yytMember.setId(id);
        yytMember.setPhone(phone);
        yytMemberService.updateById(yytMember);
        return ResponseResult.success("绑定成功！");
    }

    /**
     * 获取物流信息
     * @return
     */
    @PostMapping("/getLogistics")
    public ResponseResult getLogistics(@RequestBody LogisticsVo logisticsVo){
        Object accessToken = weXinConfig.getAccessToken();
        Map map = (Map) accessToken;
        String access_token = map.get("access_token").toString();
        String url = "https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/trace_waybill?access_token=" + access_token;
        JSONObject result = restTemplate.postForObject(url, logisticsVo, JSONObject.class);
        System.out.println(result);

        return ResponseResult.success(result);
    }
}
